import Loading from '@/components/Loading';
import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import { sourceUrl } from '@/config';
import searchImage from '@/giftCardSubPack/images/coupon/search.png';
import { debounce } from '@/utils/helper.js';
import utils from '@/utils/index';
import { Image, Input, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import Icon from '@/components/Icon';
import './index.scss';

const CouponProductItem = ({
  item: { title, price, url, quantity, optionValue = '' },
  item,
  addProduct,
}) => {
  const thePrice = parseFloat(price).toFixed(2);

  return (
    <View className="product">
      <View className="left">
        <Image
          className="product-img"
          src={url?.indexOf('http') === 0 ? url : sourceUrl + url}
        ></Image>
      </View>
      <View className="right">
        <View className="info">
          <View className="name">{title}</View>
          <View className="intro">{optionValue}</View>
          <View className="pricePay">
            <View className="realPrice">
              <Text className="zUnit customePageStyle">¥</Text>
              <Text className="zNum customePageStyle">{parseInt(thePrice)}</Text>
              <Text className="zUnit customePageStyle">{utils.getDotStr(thePrice)}</Text>
            </View>
            {quantity !== undefined && <View className="saleNum">{quantity}人付款</View>}
          </View>
          <Icon
            name="icon_shopping"
            className="add"
            size={32}
            onClick={() => {
              addProduct(item);
            }}
          />
        </View>
      </View>
    </View>
  );
};

const CouponProducts = ({
  dispatch,
  couponProductSumPrice,
  couponProductList,
  couponProductListFinished,
  couponProductCouponInfo,
}) => {
  const { params: { configId, couponId, sourceType, name } = {} } = useRouter();

  let minAmount = 0,
    restPrice = 0;
  if (sourceType == 1) {
    minAmount = couponProductCouponInfo?.minAmount ?? 0;
    restPrice = minAmount - couponProductSumPrice;
  }

  // 搜索
  const [productName, setProductName] = useState('');
  const searchVal = useRef('');
  const handleSearchInput = (e) => {
    searchVal.current = e.detail.value ?? '';
  };

  const handleSearchConfirm = debounce(() => {
    setProductName(searchVal.current);
  }, 500);

  // 获取记录
  const getNextList = useCallback(
    (params) => {
      dispatch({
        type: 'giftCard/fetchCouponProductList',
        payload: {
          sourceType,
          configId,
          couponId,
          productName,
          pageSize: 10,

          ...params,
        },
      });
    },
    [configId, couponId, sourceType, productName],
  );

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !couponProductListFinished && couponProductList?.length > 0 && getNextList();
  }, 1200);

  // 离开页面, 清空数据
  useEffect(() => {
    return () => {
      dispatch({
        type: 'giftCard/resetCouponProductsInfo',
      });
    };
  }, []);

  // 获取列表数据
  useEffect(() => {
    getNextList({ page: 1 });
  }, [getNextList]);

  // 获取在购物车中的适合这次优惠券的商品总价
  useEffect(() => {
    if (!couponId || sourceType == 0) {
      return;
    }

    dispatch({
      type: 'giftCard/getCouponProductInCartPrice',
      payload: { configId, sourceType },
    });
  }, [configId]);

  const addProduct = debounce(async (product) => {
    const {
      productReleaseId,
      productVariantReleaseId,
      orgId,
      orgName,
      merchantId,
      favouredId,
      favouredType,
      storeType,
    } = product;

    const res = await dispatch({
      type: 'productList/addProduct',
      payload: {
        productReleaseId,
        productVariantReleaseId,
        orgId,
        orgName,
        merchantId,
        favouredId,
        favouredType,
        // 后端 接口不统一, 在商品这边为2, 在购物车这边为1
        type: storeType === 2 ? 1 : storeType,
        num: 1,
      },
    });

    // 加入购物车失败
    if (res.code !== '1') {
      Taro.showToast({
        title: res.message || '加入购物车失败,请重试',
        icon: 'none',
        duration: 1500,
      });

      return;
    }

    if (sourceType == 1) {
      await dispatch({
        type: 'giftCard/addProductToCouponProductSumPrice',
        payload: product.price,
      });
    }

    Taro.showToast({
      title: '加入购物车成功',
      icon: 'none',
    });
  }, 1000);

  return (
    <>
      <DefaultNavBar title={'用券促销：' + name} />
      <View className="couponProducts">
        <View className="couponProductsTop">
          <View className="search-bar">
            <Image src={searchImage} className="search-image"></Image>
            <Input
              className="input"
              type="text"
              placeholder="搜索商品"
              placeholderClass="inputPlaceholder"
              onInput={handleSearchInput}
              onConfirm={handleSearchConfirm}
            />
          </View>
        </View>
        <ScrollView
          className="product-products"
          scrollY
          style={{
            height: `calc(100vh - ${Taro.$titleHeight}px - ${
              Taro.$statusBarHeight
            }px - ${utils.getSizeByScale(100)}px - ${utils.getSizeByScale(98)}px)`,
          }}
          onScrollToLower={handleScrollToLower}
        >
          {couponProductList?.map((item) => {
            return (
              <CouponProductItem
                key={item.productReleaseId + '|' + item.productVariantReleaseId}
                item={item}
                addProduct={addProduct}
              ></CouponProductItem>
            );
          })}

          <Loading
            loading={!couponProductListFinished}
            finished={couponProductListFinished && couponProductList?.length >= 8}
          />
        </ScrollView>

        <View className="bottom-info">
          <View className="left">
            {sourceType == 1 && (
              <>
                <View className="summary flex-row--center">
                  <Text className="desc">合计：</Text>
                  <Text className="num customePageStyle">
                    ¥{parseFloat(couponProductSumPrice).toFixed(2)}
                  </Text>
                </View>
                {restPrice <= 0 ? null : (
                  <View className="info">
                    再买
                    <Text className="num">{parseFloat(restPrice).toFixed(2)}</Text>
                    元可享受优惠
                  </View>
                )}
              </>
            )}
          </View>
          <View className="right">
            <View
              className="cartBtn customePageBackgroundStyle flex-row-center-center"
              onClick={() => {
                Taro.redirectTo({ url: '/pages/mainPages/cartSin/index' });
              }}
            >
              去购物车
            </View>
          </View>
        </View>
      </View>
    </>
  );
};
export default connect(({ giftCard }) => ({
  couponProductSumPrice: giftCard.couponProductSumPrice,
  couponProductList: giftCard.couponProductList,
  couponProductCouponInfo: giftCard.couponProductCouponInfo,
  couponProductListFinished: giftCard.couponProductListFinished,
}))(CouponProducts);
